package Demo08.Demo0830;

public class HomeWork {
    public static void main(String[] args) {
        //给定一个整型数组, 实现冒泡排序(升序排序)
      /*  int[] a = new int[]{5,1,3,4,6,8,2,7};
        Bubble(a,a.length);
        for(int i : a){
            System.out.print(i + " ");
        }*/
        //给定一个整型数组, 判定数组是否有序（递增）
       /* int[] a = {1,2,3,4,5,6};
        int[] b = {1,2,4,3,5,6};
        System.out.println(increase(a,a.length));
        System.out.println(increase(b,b.length));*/
        //给定一个有序整型数组, 实现二分查找
        /*int[] a = {1,2,3,4,5,6,7,8,9};
        System.out.println(binarySearch(a,1));*/
        //实现一个方法 copyOf, 对一个整型数组进行拷贝, 得到一个新的数组.
        /*int[] a = new int[]{9,5,2,7,8,8,6};
        int[] b = copyOf(a,a.length);
        for(int i: b){
            System.out.print(i + " ");
        }*/
        //实现一个方法 toString, 把一个整型数组转换成字符串. 例如数组 {1, 2, 3} , 返回的字符串为 "[1, 2, 3]", 注意 逗号 的位置和数量.
        int[] a = new int[]{9,5,2,7,8,8};
        String str = toString(a);
        System.out.println(str);
    }
    public static String toString(int[] a){
        String str = "";
        for (int i = 0; i < a.length; i++) {
            if(i == 0){
                str += "[" + a[i] + ",";
            }else if(i == a.length - 1){
                str += a[i - 1] + "]";
            }else{
                str += a[i] + ",";
            }
        }
        return str;
    }
    public static int[] copyOf(int[] a,int b){
        int[] arr = new int[b];
        for (int i = 0; i < b; i++) {
            arr[i] = a[i];
        }
        return arr;
    }
    public static int binarySearch(int[] a,int key){
        int left = 0;
        int right = a.length - 1;
        while(left <= right){// 这里我唯一的疑问就是，当我的条件是 right > left的时候，总会有各种各样的异常，但是如果是left <= right的话就可以
            int mid =left + ((right - left) >> 1);
            if(a[mid] == key){
                return mid;
            }else if(key > a[mid]){
                left = mid + 1;
            }else{
                right = mid - 1;
            }
        }
        return -1;//没有找到返回 - 1
    }
    public static boolean increase(int[] a,int b){
        int count = 0;//计数器，来判定是否有不是递增的情况
        for (int i = 0; i < a.length - 1; i++) {
            if(a[i] > a[i + 1]){
                count++;
            }
        }
        return count == 0 ? true : false;
    }
    public static void Bubble(int[] a,int b){
        for (int i = b - 1; i >= 0; i--) {
            for (int j = 0; j < i; j++) {
                if(a[j] > a[j + 1]){
                    int tmp = a[j];
                    a[j] = a[j + 1];
                    a [j + 1] = tmp;
                }
            }
        }
    }
}
